#include <iostream>

struct ListNode
{
    int val;
    ListNode* next;

    ListNode(int val) :val(val), next(nullptr){}
};

//创建链表
ListNode* CreateList()
{
    ListNode* node1 = new ListNode(1);
    ListNode* node2 = new ListNode(2);
    ListNode* node3 = new ListNode(3);
    ListNode* node4 = new ListNode(4);
    ListNode* node5 = new ListNode(5);
    ListNode* node6 = new ListNode(6);

    node1->next = node2;
    node2->next = node3;
    node3->next = node4;
    node4->next = node5;

    node5->next = node3;

    return node1;
}

ListNode *reverseList(ListNode *head)
{
    // 如果链表为空，或者只有一个节点的话，直接返回
    if (head == nullptr || head->next == nullptr)
        return head;

    ListNode *cur_node = head;
    ListNode *next_node = head;
    ListNode *prev_node = nullptr;

    while (cur_node)
    {
        // 找到下一个节点
        next_node = next_node->next;
        // 反转
        cur_node->next = prev_node;
        // 更新节点
        prev_node = cur_node;
        cur_node = next_node;
    }
    return prev_node;
}
